<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative; ">
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <q-breadcrumbs-el label="项目列表" />
        <el-button type="primary" size="small" @click="toCreatePage"
          style="max-width: 200px;position: absolute;right: 0;">新建项目
        </el-button>
      </q-breadcrumbs>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="全部项目" name="1">
        <q-tab-panels v-model="tab" vertical transition-prev="jump-up" transition-next="jump-up">
          <q-tab-panel name="participation">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="project in collectProjects" :key="project.id">
                <el-card style="position: relative;margin-bottom: 20px;" shadow="hover">
                  <div
                    style="display:flex;cursor: pointer;width: 100%;background-color: rgb(46,130,200);height: 120px;margin: 0"
                    @click="toPage(project.id)">
                    <div class="q-ml-md"
                      style="margin: 0;padding:20px;box-sizing: border-box;font-size: 16px; color: #3c4043; font-weight: 500">
                      <span style="color: #FFFFFF">{{ project.title }}</span><br>
                      <span style="font-size:12px;color: #FFFFFF">{{ project.description }}</span>
                    </div>
                  </div>
                  <div
                    style="display: flex;align-items: center;justify-content: center;line-height: 40px;text-align: center">
                    <span>创建人:</span>
                    <el-avatar style="margin: 0 10px" :size="26" src="https://cdn.quasar.dev/img/avatar2.jpg" />
                    <span>qwd@zilixir.com</span>
                  </div>
                  <div style="position: absolute; right:15px;top:15px;font-size: 20px;cursor: pointer;"
                    class="text-primary" @click="isCollectProject(project)">
                    <el-image v-if="!project.is_star" :src="noCollect" class="star"></el-image>
                    <el-image v-else :src="collect" class="star"></el-image>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </q-tab-panel>
        </q-tab-panels>
      </el-tab-pane>
      <el-tab-pane label="我创建的" name="2">
        <q-tab-panels v-model="tab" vertical transition-prev="jump-up" transition-next="jump-up">
          <q-tab-panel name="participation">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="project in creatorList" :key="project.id">
                <el-card style="position: relative;margin-bottom: 20px;" shadow="hover">
                  <div
                    style="display:flex;cursor: pointer;width: 100%;background-color: rgb(46,130,200);height: 120px;margin: 0"
                    @click="toPage(project.id)">
                    <div class="q-ml-md"
                      style="margin: 0;padding:20px;box-sizing: border-box;font-size: 16px; color: #3c4043; font-weight: 500">
                      <span style="color: #FFFFFF">{{ project.title }}</span><br>
                      <span style="font-size:12px;color: #FFFFFF">{{ project.description }}</span>
                    </div>
                  </div>
                  <div
                    style="display: flex;align-items: center;justify-content: center;line-height: 40px;text-align: center">
                    <span>创建人:</span>
                    <el-avatar style="margin: 0 10px" :size="26" src="https://cdn.quasar.dev/img/avatar2.jpg" />
                    <span>qwd@zilixir.com</span>
                  </div>
                  <div style="position: absolute; right:15px;top:15px;font-size: 20px;cursor: pointer;"
                    class="text-primary" @click="ElMessage.warning('功能开发中 ...')">
                    <q-icon name="star">
                      <el-image v-if="!project.is_star" :src="noCollect" class="star"></el-image>
                      <el-image v-else :src="collect" class="star"></el-image>
                    </q-icon>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </q-tab-panel>
        </q-tab-panels>
      </el-tab-pane>
      <el-tab-pane label="我管理的" name="3">
        <q-tab-panels v-model="tab" vertical transition-prev="jump-up" transition-next="jump-up">
          <q-tab-panel name="participation">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="project in adminList" :key="project.id">
                <el-card style="position: relative;margin-bottom: 20px;" shadow="hover">
                  <div
                    style="display:flex;cursor: pointer;width: 100%;background-color: rgb(46,130,200);height: 120px;margin: 0"
                    @click="toPage(project.id)">
                    <div class="q-ml-md"
                      style="margin: 0;padding:20px;box-sizing: border-box;font-size: 16px; color: #3c4043; font-weight: 500">
                      <span style="color: #FFFFFF">{{ project.title }}</span><br>
                      <span style="font-size:12px;color: #FFFFFF">{{ project.description }}</span>
                    </div>
                  </div>
                  <div
                    style="display: flex;align-items: center;justify-content: center;line-height: 40px;text-align: center">
                    <span>创建人:</span>
                    <el-avatar style="margin: 0 10px" :size="26" src="https://cdn.quasar.dev/img/avatar2.jpg" />
                    <span>qwd@zilixir.com</span>
                  </div>
                  <div style="position: absolute; right:15px;top:15px;font-size: 20px;cursor: pointer;"
                    class="text-primary" @click="ElMessage.warning('功能开发中 ...')">
                    <q-icon name="star">
                      <el-image v-if="!project.is_star" :src="noCollect" class="star"></el-image>
                      <el-image v-else :src="collect" class="star"></el-image>
                    </q-icon>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </q-tab-panel>
        </q-tab-panels>
      </el-tab-pane>
      <el-tab-pane label="我参与的" name="4">
        <q-tab-panels v-model="tab" vertical transition-prev="jump-up" transition-next="jump-up">
          <q-tab-panel name="participation">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="project in participateList" :key="project.id">
                <el-card style="position: relative;margin-bottom: 20px;" shadow="hover">
                  <div
                    style="display:flex;cursor: pointer;width: 100%;background-color: rgb(46,130,200);height: 120px;margin: 0"
                    @click="toPage(project.id)">
                    <div class="q-ml-md"
                      style="margin: 0;padding:20px;box-sizing: border-box;font-size: 16px; color: #3c4043; font-weight: 500">
                      <span style="color: #FFFFFF">{{ project.title }}</span><br>
                      <span style="font-size:12px;color: #FFFFFF">{{ project.description }}</span>
                    </div>
                  </div>
                  <div
                    style="display: flex;align-items: center;justify-content: center;line-height: 40px;text-align: center">
                    <span>创建人:</span>
                    <el-avatar style="margin: 0 10px" :size="26" src="https://cdn.quasar.dev/img/avatar2.jpg" />
                    <span>qwd@zilixir.com</span>
                  </div>
                  <div style="position: absolute; right:15px;top:15px;font-size: 20px;cursor: pointer;"
                    class="text-primary" @click="ElMessage.warning('功能开发中 ...')">
                    <q-icon name="star">
                      <el-image v-if="!project.is_star" :src="noCollect" class="star"></el-image>
                      <el-image v-else :src="collect" class="star"></el-image>
                    </q-icon>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </q-tab-panel>
        </q-tab-panels>
      </el-tab-pane>
    </el-tabs>
    <!--    <el-dialog-->
    <!--      v-model="projectStore.blockVisible"-->
    <!--      title="选择项目"-->
    <!--      width="600px"-->
    <!--      :show-close="false"-->
    <!--      :close-on-click-modal="false"-->
    <!--    >-->
    <!--      <div class="dialogContent">-->
    <!--        <div class="dialogLeft">选择项目进入:</div>-->
    <!--        <div class="dialogRight">-->
    <!--          <el-menu-->
    <!--            :default-active="activeIndex"-->
    <!--            active-text-color="#0000ff"-->
    <!--            background-color="#fff"-->
    <!--            class="el-menu-demo"-->
    <!--            text-color="#000"-->
    <!--            unique-opened="true"-->
    <!--            @select="handleSelect"-->
    <!--          >-->
    <!--            <el-sub-menu index="1">-->
    <!--              <template #title>-->
    <!--                <el-icon>-->
    <!--                  <House/>-->
    <!--                </el-icon>-->
    <!--                <span>全部项目</span>-->
    <!--              </template>-->
    <!--              <template v-for="(project,index) in collectProjects" :key="project.id">-->
    <!--                <el-menu-item :index="'1-'+index+1" @click="getProjectId(project)">{{ project.title }}</el-menu-item>-->
    <!--              </template>-->
    <!--            </el-sub-menu>-->
    <!--            <el-sub-menu index="2">-->
    <!--              <template #title>-->
    <!--                <el-icon>-->
    <!--                  <Folder/>-->
    <!--                </el-icon>-->
    <!--                <span>我创建的项目</span>-->
    <!--              </template>-->
    <!--              <template v-for="(project,index) in creatorList" :key="project.id">-->
    <!--                <el-menu-item :index="'2-'+index+1" @click="getProjectId(project)">{{ project.title }}</el-menu-item>-->
    <!--              </template>-->
    <!--            </el-sub-menu>-->
    <!--            <el-sub-menu index="3">-->
    <!--              <template #title>-->
    <!--                <el-icon>-->
    <!--                  <User/>-->
    <!--                </el-icon>-->
    <!--                <span>我管理的项目</span>-->
    <!--              </template>-->
    <!--              <template v-for="(project,index) in adminList" :key="project.id">-->
    <!--                <el-menu-item :index="'3-'+index+1" @click="getProjectId(project)">{{ project.title }}</el-menu-item>-->
    <!--              </template>-->
    <!--            </el-sub-menu>-->
    <!--            <el-sub-menu index="4">-->
    <!--              <template #title>-->
    <!--                <el-icon>-->
    <!--                  <User/>-->
    <!--                </el-icon>-->
    <!--                <span>我参与的项目</span>-->
    <!--              </template>-->
    <!--              <template v-for="(project,index) in participateList" :key="project.id">-->
    <!--                <el-menu-item :index="'4-'+index+1" @click="getProjectId(project)">{{ project.title }}</el-menu-item>-->
    <!--              </template>-->
    <!--            </el-sub-menu>-->
    <!--          </el-menu>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--      <template #footer>-->
    <!--        <span class="dialog-footer">-->
    <!--          <div class="button" @click="closeDialog">取消</div>-->
    <!--          <div-->
    <!--            class="button"-->
    <!--            @click="toEnterProject"-->
    <!--          >进入项目</div>-->
    <!--        </span>-->
    <!--      </template>-->
    <!--    </el-dialog>-->


    <el-dialog v-model="createProjectDialogVisible" title="新建项目" width="500px" :close-on-click-modal="false">
      <div style="margin-top: 20px">
        <el-form :model="newProjectData" :rules="newProjectDataRules" label-width="80px" ref="createPorjectRef"
          @submit.prevent>
          <el-form-item label="项目名称" prop="title">
            <el-input placeholder="请输入项目名称" v-model="newProjectData.title"></el-input>
          </el-form-item>
          <el-form-item label="项目描述">
            <el-input type="textarea" placeholder="请输入" :rows="3" v-model="newProjectData.description" show-word-limit
              maxlength="100"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="createProjectDialogFooter">
          <el-button @click="createProjectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createProject(createPorjectRef)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </q-page>
</template>
<script setup lang="ts">
import { reactive, ref, watch, onMounted } from "vue";
import collect from 'assets/dataSet/collect.png'
import noCollect from 'assets/dataSet/no_collect.png'
import {
  checkIsRepeatofProject,
  collectProject,
  createProject as createProjectApi,
  getProjectList,
  isQuickStart
} from "src/api/project";
import { useMenuStore } from 'src/stores/menu';
import { useRouter } from 'vue-router';
import { dataSetStore } from 'src/stores/dataSet'
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { isMemberInterface } from "src/api/user";
import { useCurrentProjectStore } from "stores/current-project";
const store = dataSetStore()
const collectProjects = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const tab = ref('participation')

const menuStore = useMenuStore()

const router = useRouter()

let activeName = ref('1')
let creatorList = ref([]);//我创建的
let adminList = ref([]);//我管理的
let participateList = ref([]);//我参与的
let projectId = ref(0);//项目的id
const projectStore = useCurrentProjectStore()
onMounted(() => {
  getQuickStartState()
})
// 获取快速入门状态
function getQuickStartState() {
  isQuickStart().then((res: any) => {
    store.setIsQuickStart(res.data.quick_start)
  })
}

//收藏/取消收藏项目
function isCollectProject(project: any) {
  let currentProjectIsStar = project.is_star;
  const id = project.id;
  if (!currentProjectIsStar) {
    //收藏逻辑
    collectProject(id, { is_star: 0 }).then(res => {
      ElMessage.success('收藏项目成功！');
      getProjects();
    })
  } else {
    //取消收藏逻辑
    ElMessageBox.confirm('确定取消收藏该项目吗？', '收藏项目', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(() => {
      collectProject(id, { is_star: 1 }).then(res => {
        ElMessage.success('取消收藏项目成功！');
        getProjects();
      })
    })
  }
}


//创建项目 start
const createPorjectRef = ref()
let createProjectDialogVisible = ref(false)
const newProjectData = reactive({
  title: '',
  description: ''
})

const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请填写项目名称'))
  }
  checkIsRepeatofProject({ project_name: value }).then((res: any) => {
    if (res.data.msg) {
      return callback(new Error(res.data.msg));
    } else {
      callback();
    }
  }).catch((error: any) => {
    return callback(new Error(error.data.msg));
  })
}

const newProjectDataRules = reactive({
  title: [{ required: true, validator: validateTitle, trigger: ['blur'] }],
})

//项目初始化
initProject();
function initProject() {
  useMenuStore().setProjectManage(false);//隐藏项目搜索框
  projectStore.setCurrentProject(0);
  // projectStore.setBlockVisible(true);
}

//创建项目 end
getProjects();

//判断页面初始化时，当前路由是否包含当前项目，如果存在，那么删除
havCurrentProject();

function havCurrentProject() {
  let menuArrayList = menuStore.menuItems.filter((item: any) => {
    if (item.currentProject) {
      return true
    } else {
      return false
    }
  })
  if (menuArrayList.length > 0) {
    menuStore.deleteMenuItems();
  }
}

function getProjects() {
  loading.value = true
  getProjectList().then((res) => {
    collectProjects.value = res.data;
    menuStore.setAllMenuList(res.data);
    creatorList.value = res.data.filter((item: any) => item.category.is_creator);//我创建的
    adminList.value = res.data.filter((item: any) => item.category.is_admin);//我管理的
    participateList.value = res.data.filter((item: any) => item.category.only_participate);//我参与的
    loading.value = false;
  }).finally(() => {
    loading.value = false
  })
}

//点击确定开始创建项目
const createProject = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      createProjectDialogVisible.value = true
      createProjectApi(newProjectData).then((res) => {
        dialogVisible.value = false
        ElMessage.success('创建项目成功！')
        getProjects();
        formEl.resetFields();
      }).finally(() => {
        createProjectDialogVisible.value = false
      })
    }
  })
}

//打开新建项目
function toCreatePage() {
  createProjectDialogVisible.value = true;
}


function toPage(id: any) {
  projectStore.setCurrentProject(id)
  // menuStore.restoreMenuItems();
  useMenuStore().setProjectManage(true);//开启项目搜索框
  isMember(id);
}

watch(() => dataSetStore().loginDialog, () => {
  dialogVisible.value = true;
  projectStore.setBlockVisible(true);
});

function isMember(id: any) {
  isMemberInterface(id).then(res => {
    const menuList = JSON.parse(JSON.stringify(collectProjects.value));
    const current = menuList.filter((item: any) => item.id === id);//当前项目
    const removeCurrntProject = menuList.filter((item: any) => item.id !== id);//除了当前项目外全部的其他项目
    let obj = {
      currentProject: true,
      ...current[0],
      children: removeCurrntProject,
      current: current[0]
    };
    menuStore.setProjectManage(true)
    menuStore.addMenuItems(obj)
    menuStore.setCurrentProject(obj);
    if (store.isQuickStart && !JSON.parse(localStorage.user).is_admin) {
      router.push({ name: 'quick-start', params: { project_id: id } })
    } else {
      router.push({ name: 'project-detail', params: { project_id: id } })
    }

    let userInfo = JSON.parse(localStorage.getItem('user') as any)
    userInfo['status'] = res.data.status;
    localStorage.setItem('user', JSON.stringify(userInfo))

  }).catch(() => {
    ElMessage.error('获取项目创建人或管理员接口报错！');
  })
}

const activeIndex = ref('1-1');


</script>
<style scoped lang="scss">
.star {
  width: 25px;
  height: 25px;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 0;
}

::v-deep .el-card__body {
  padding: 0;
}

::v-deep .el-dialog__header {
  margin: 0;
  border-bottom: 1px solid;
}

::v-deep .q-item {
  background-color: #FFFFFF;
}

::v-deep .el-menu {
  border: none;
}

::v-deep .el-dialog__body {
  padding-top: 0;
}

.el-menu ::v-deep(.el-sub-menu.is-active > .el-sub-menu__title) {
  color: #0000ff !important;
}

.project-page .q-tab {
  height: 40px;
  font-size: 16px;
}

.createProjectDialogFooter {
  display: flex;
  position: absolute;
  right: 0 !important;
  bottom: 0;
  width: 100%;
  border: none !important;

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid;
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}

.dialogContent {
  display: flex;
  justify-content: space-between;
  vertical-align: top;
  width: 350px;
  margin: 0 auto;
}

.dialogLeft {
  flex: 1;
  padding-top: 17px;
  font-size: 13px;
  color: #1d1d1d;
  font-weight: bold;
}

.dialogRight {
  flex: 3;
  height: 230px;
  overflow: auto;
}

.acitve-item {

  svg,
  .q-item__section--avatar i {
    color: $primary;
  }
}

.createProjectDialogFooter {
  display: flex;
  justify-content: flex-end;
  position: absolute;
  bottom: 20px;
  width: 100%;
  padding-right: 20px;
  border-top: none;
  box-sizing: border-box;

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid;
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}

.dialog-footer {
  display: flex;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid;

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid;
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}
</style>

